package com.xieyong.mywebsite.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xieyong.mywebsite.mapper.ArticleMapper;
import com.xieyong.mywebsite.model.dto.PageBean;
import com.xieyong.mywebsite.model.entity.Article;
import com.xieyong.mywebsite.service.ArticleService;
import com.xieyong.mywebsite.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateId(id);
        article.setUpdateId(id);
        articleMapper.insert(article);
    }

    @Override
    public void delete(Integer id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer operatorId = (Integer) map.get("id");
        articleMapper.delete(id,operatorId,LocalDateTime.now());
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setUpdateId(id);
        articleMapper.update(article);
    }

    @Override
    public PageInfo<Article> findByCondition(Integer pageNum, Integer pageSize, LocalDateTime startTime,LocalDateTime endTime, Article article) {
////        创建分页dto对象
//        PageBean<Article> pageBean = new PageBean<>();
////        开启分页查询
//        PageHelper.startPage(pageNum, pageSize);
////        调用mapper查询数据
//        Map<String, Object> map = ThreadLocalUtil.get();
//        article.setCreateId((Integer) map.get("id"));
////
//        Page<Article> articles = articleMapper.selectByCondition(article); // 这里将查询到的数据给pageHelper提供的page对象
//
////        把数据填充到PageBean对象中
//        pageBean.setTotal(articles.getTotal());
//        pageBean.setItems(articles.getResult());
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articles = articleMapper.selectByCondition(startTime,endTime,article);
        return PageInfo.of(articles);
    }

    @Override
    public Article detail(Integer id) {
        return articleMapper.selectById(id);
    }

    @Override
    public List<Article> list() {
        return articleMapper.selectAll();
    }
}
